import bezierSwipe from '@/utils/bezierSwipe';
// 去除限制
const removeLimit = () => {
    importClass(com.stardust.autojs.core.accessibility.AccessibilityBridge.WindowFilter);
    let bridge = runtime.accessibilityBridge;
    let bridgeField = runtime.getClass().getDeclaredField("accessibilityBridge");
    let configField = bridgeField.getType().getDeclaredField("mConfig");
    configField.setAccessible(true);
    configField.set(bridge, configField.getType().newInstance());
    bridge.setWindowFilter(new JavaAdapter(AccessibilityBridge$WindowFilter, {
        filter: function (info) {
            return true;
        }
    }));
}
// 获取IMEI
const getIMEI = () => device.sdkInt < 29 ? device.getIMEI() : device.getAndroidId();
// 
/**
 * 自定义控制台
 * @param {string} tit 控制台标题
 * @param {Object} position 控制台位置 {x: '', y: ''}
 */
const consoleCustom = (tit = '脚本精灵', position = { x: 30, y: 100}) => {
    importClass(Packages.androidx.recyclerview.widget.RecyclerView);
    console.show();
    console.setPosition(position.x, position.y);
    function getConsoleWindow() {
        let mConsole = runtime.console;
        let field = mConsole.class.superclass.getDeclaredField("mConsoleFloaty");
        field.setAccessible(true);
        let mConsoleFloaty = field.get(mConsole);
        let mConsoleView = mConsoleFloaty.getExpandedView();
        return mConsoleView;
    };
    let mConsoleView = getConsoleWindow();
    let parent = mConsoleView.parent;
    var inputView = parent.findViewById(context.getResources().getIdentifier("input", "id", context.getPackageName()));
    var buttonView = parent.findViewById(context.getResources().getIdentifier("submit", "id", context.getPackageName()));
    let titleView = parent.findViewById(context.getResources().getIdentifier("title", "id", context.getPackageName()));
    titleView.setText(tit);
    ui.run(function () {
        inputView.setVisibility(8);
        buttonView.setVisibility(8);
    });
};
/**
 * 不能点击的控件，通过坐标点击
 **/
const clickUiBounds = (ui) => {
    if (ui.exists()) {
        var a = ui.findOnce();
        if (a) {
            var b = a.bounds();
            if (b) {
                click(b.centerX(), b.centerY());
                return true;
            }
        }
    }
    return false;
};
/**
 * 点击UI上的控件 clickControl(id("iv_fc_red_close"));
 * @param {UI上的元素} element 
 */
function clickControl(element) {
    let clickResult = false;
    if (element == null) {
        return false;
    }
    try {
        if (element.exists()) {
            toastLog("准备click：" + element);
            let clickable = element.findOnce().clickable(); //是否可以点击
            if (clickable) {
                clickResult = element.findOnce().click();
                sleep(random(2000, 3200));
            } else {
                let b = element.findOnce().bounds();
                clickResult = click(b.centerX(), b.centerY());
                sleep(random(2000, 3200));
            }
        }
        return clickResult;
    } catch (error) {
        toastError("clickControl方法出现错误：" + error)
        return false;
    }

}
/**
 * 设置storage
 */
const setStorages = (name, key, val) => {
    const storage = storages.create(name);
    storage.put(key, val);
};
/**
 * 读取storage
 */
const getStorages = (name, key, val) => {
    const storage = storages.create(name);
    if (storage.contains(key)) {
        return storage.get(key, null);
    };
    return null;
};
// 判断网络状态
function networkInfo() {
    importClass(android.net.ConnectivityManager);
    var mConnectivityManager = context.getSystemService(context.CONNECTIVITY_SERVICE);
    netInfo = mConnectivityManager.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isAvailable()) {
        // 网络连接
        var name = netInfo.getTypeName();
        if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            // WiFi网络
            return "WIFI"
        } else if (netInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
            // 有线网络
            return "有线"

        } else if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            // 3g网络
            return "移动"

        } else {
            return "未知"
        }
    } else {
        // 网络断开
        return "断开"
    }
}
//清理缓存,如果缓存空间不足
function checkSpace() {
    if (textStartsWith('存储空间').exists() && text('取消').exists()) {
        var o = text('取消').findOnce();
        if (o) {
            clickui(o);
            sleep(1000);
        }

        if (device.sdkInt > 24) {
            var intent = new Intent();
            intent.setAction("android.settings.INTERNAL_STORAGE_SETTINGS"); //MEMORY_CARD_SETTINGS
            app.startActivity(intent);
            sleep(3000);


            var o = text('缓存数据').findOnce(); //小米
            if (o) {
                clickui(o);
                sleep(1000);
                if (text('取消').exists() && text('确定').exists()) {
                    var o = text('确定').findOnce();
                    clickui(o);
                    sleep(10000);
                }
            }

            swipe(100, 200, 100, 500, 500); //z注意,这里需要修改.这里是用于滑动的
            var o = text('垃圾清理').findOnce(); //小米
            if (o.length > 0) {
                // clickObject(o[o.length - 1]);
                o.click()
                sleep(3000);
                var iii = 10;
                while (iii-- > 0) {
                    if (textStartsWith('清理选中垃圾').exists()) {
                        var o = textStartsWith('清理选中垃圾').findOnce();
                        o.click()
                        sleep(5000);
                        back();
                        break;
                    } else
                        sleep(5000);
                }
            }
        } else {
            app.startActivity({
                action: "android.settings.INTERNAL_STORAGE_SETTINGS",
                root: true
            });
            sleep(8000);

            var o = text('缓存数据').findOnce(); //小米
            if (o) {
                o.click();
                sleep(1000);
                if (text('取消').exists() && text('确定').exists()) {
                    var o = text('确定').findOnce();
                    clickui(o);
                    sleep(10000);
                }
            }
        }

        back();
    }
}

/**
 * 获取IP地址和IP所在地
 */
function getIpAdressAndIpGps() {
    try {
        let ip = ""
        let address = ""
        let response = http.get('http://pv.sohu.com/cityjson?ie=utf-8');
        if (response.statusCode == 200) {
            toastLog("sohu")
            let InetIP = response.body.string()
            eval(InetIP)
            ip = (returnCitySN.cip)
            address = (returnCitySN.cname)
        } else {
            toastLog("baidu")
            let ip_gps = false
            let ip_regx = /本机IP:&nbsp;\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}<\/span>([\s\S]*?)<\/td/
            let ipUrl = "http://www.baidu.com/s?ie=UTF-8&wd=ip%E5%BD%92%E5%B1%9E%E5%9C%B0%E6%9F%A5%E8%AF%A2" //百度的
            let response = http.get(ipUrl);
            if (response.statusCode == 200) {
                let htmlResult = response.body.string()
                ip_gps = ip_regx.exec(htmlResult)
                let responseRex = ip_regx.exec(ip_gps)
                ip = responseRex[0].split(";")[1].split("</span>")[0]
                address = responseRex[1]
            }
        }
        return ip + "@" + address
    } catch (error) {
        return "获取IP和所在地失败" + "@" + error
    }
}
/**
 * 获取日期格式输出
 * @param  {Date}   time   时间
 * @param  {String} format 输出格式，要求必须含有yyyy,mm,dd
 * @return {String}        默认返回yyyymmdd格式时间
 */
const getTimeStr = (time, format = 'yyyy-MM-dd') => {
    if (typeof time === 'string' || typeof time === 'number') {
        time = new Date(time);
    }
    return format
        .replace('yyyy', time.getFullYear())
        .replace('MM', leftpad(time.getMonth() + 1, 2, '0'))
        .replace('dd', leftpad(time.getDate(), 2, '0'))
        .replace('HH', leftpad(time.getHours(), 2, '0'))
        .replace('mm', leftpad(time.getMinutes(), 2, '0'))
        .replace('ss', leftpad(time.getSeconds(), 2, '0'));
}
// 设置按比例缩放点击坐标, 待测试
function clicks(x, y) {
    setScreenMetrics(1080, 1920);
    x1 = device.width / 1080
    y1 = device.height / 1920
    click(x * x1, y * y1)
}
/**
 * 获取手机联系人  需要读取用户通讯录权限
 */
const getUserPhoneList = () => {
    importClass(android.database.Cursor);
    var cursor = context.getContentResolver().query(android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
    while (cursor.moveToNext()) {
        //读取通讯录的姓名
        var name = cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        //读取通讯录的号码
        var number = cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER));
        if (name != number) {
            log("[名字]：" + name + " [号码]：" + number);
        } else {
            log("[号码]：" + number);
        }
    }
}
 
export {
    removeLimit,
    getIMEI,
    consoleCustom,
    clickUiBounds,
    setStorages,
    getStorages,
    getTimeStr,
    bezierSwipe,
}